Page({
  data: {
    canvasWidth: 0,
    canvasHeight: 0,
    score: 0,
    level: 1,
    health: 10,
    gameOver: false,
    gamePaused: false,
    showPauseMenu: false
  },

  onLoad() {
    this.initGame()
  },

  onReady() {
    this.initCanvas()
    this.startGameLoop()
  },

  onUnload() {
    this.stopGameLoop()
  },

  initGame() {
    // 游戏状态初始化
    this.gameState = {
      tank: {
        x: 0,
        y: 0,
        width: 40,
        height: 40,
        speed: 5
      },
      bullets: [],
      enemyBullets: [],
      planes: [],
      lastShot: 0,
      shotCooldown: 300, // 增加射击间隔，让自动射击更合理
      planeSpawnTimer: 0,
      planeSpawnInterval: 1000,
      enemyBulletTimer: 0,
      enemyBulletInterval: 800,
      autoShoot: true // 新增：自动射击开关
    }
    
    // 触摸控制状态
    this.touchState = {
      leftPressed: false,
      rightPressed: false,
      upPressed: false
    }
    
    // 关卡提升提示
    this.levelUpMessage = null
    
    // 图片资源管理
    this.images = {
      tank: null,
      rivet: null,
      tankLoaded: false,
      rivetLoaded: false
    }
    
    // 预加载图片资源
    this.preloadImages()
  },

  // 预加载图片资源
  preloadImages() {
    // 使用微信小程序兼容的方式加载图片
    console.log('开始加载图片资源...')
    
    // 坦克图片
    this.loadTankImage()
    
    // 炮管图片
    this.loadRivetImage()
  },

  // 加载坦克图片
  loadTankImage() {
    const tankImg = wx.createImage()
    tankImg.onload = () => {
      this.images.tank = tankImg
      this.images.tankLoaded = true
      console.log('坦克图片加载成功')
    }
    tankImg.onerror = () => {
      console.log('坦克图片加载失败，使用几何图形')
      this.images.tankLoaded = false
    }
    tankImg.src = '/assets/tank.png'
  },

  // 加载炮管图片
  loadRivetImage() {
    const rivetImg = wx.createImage()
    rivetImg.onload = () => {
      this.images.rivet = rivetImg
      this.images.rivetLoaded = true
      console.log('炮管图片加载成功')
    }
    rivetImg.onerror = () => {
      console.log('炮管图片加载失败，使用几何图形')
      this.images.rivetLoaded = false
    }
    rivetImg.src = '/assets/rivet.png'
  },

  initCanvas() {
    const query = wx.createSelectorQuery()
    query.select('#gameCanvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        const canvas = res[0].node
        const ctx = canvas.getContext('2d')
        
        const dpr = wx.getSystemInfoSync().pixelRatio
        canvas.width = res[0].width * dpr
        canvas.height = res[0].height * dpr
        ctx.scale(dpr, dpr)
        
        this.canvas = canvas
        this.ctx = ctx
        this.canvasWidth = res[0].width
        this.canvasHeight = res[0].height
        
        // 设置坦克初始位置
        this.gameState.tank.x = this.canvasWidth / 2 - this.gameState.tank.width / 2
        this.gameState.tank.y = this.canvasHeight - this.gameState.tank.height - 20
        
        console.log('Canvas初始化完成')
      })
  },

  startGameLoop() {
    this.gameLoop = setInterval(() => {
      if (!this.data.gameOver && !this.data.gamePaused) {
        this.updateGame()
        this.renderGame()
      }
    }, 16) // 60 FPS
  },

  stopGameLoop() {
    if (this.gameLoop) {
      clearInterval(this.gameLoop)
    }
  },

  updateGame() {
    this.updateTank()
    this.autoShoot() // 新增：自动射击
    this.updateBullets()
    this.updateEnemyBullets()
    this.updatePlanes()
    this.spawnPlanes()
    this.spawnEnemyBullets()
    this.checkCollisions()
    this.updateLevel()
  },

  updateTank() {
    const tank = this.gameState.tank
    const step = 8
    
    // 处理触摸控制
    if (this.touchState.leftPressed) {
      tank.x = Math.max(0, tank.x - step)
    }
    if (this.touchState.rightPressed) {
      tank.x = Math.min(this.canvasWidth - tank.width, tank.x + step)
    }
    if (this.touchState.upPressed) {
      tank.y = Math.max(this.canvasHeight - tank.height - 50, tank.y - step)
    }
  },

  // 新增：自动射击功能
  autoShoot() {
    if (!this.gameState.autoShoot) return
    
    const now = Date.now()
    if (now - this.gameState.lastShot >= this.gameState.shotCooldown) {
      this.gameState.lastShot = now
      
      const tank = this.gameState.tank
      const bullet = {
        x: tank.x + tank.width / 2 - 2,
        y: tank.y - 10,
        width: 4,
        height: 8,
        speed: 8
      }
      
      this.gameState.bullets.push(bullet)
    }
  },

  updateBullets() {
    for (let i = this.gameState.bullets.length - 1; i >= 0; i--) {
      const bullet = this.gameState.bullets[i]
      bullet.y -= bullet.speed
      
      // 移除超出屏幕的子弹
      if (bullet.y < 0) {
        this.gameState.bullets.splice(i, 1)
      }
    }
  },

  updateEnemyBullets() {
    for (let i = this.gameState.enemyBullets.length - 1; i >= 0; i--) {
      const bullet = this.gameState.enemyBullets[i]
      bullet.y += bullet.speed
      
      // 移除超出屏幕的子弹
      if (bullet.y > this.canvasHeight) {
        this.gameState.enemyBullets.splice(i, 1)
      }
    }
  },

  updatePlanes() {
    for (let i = this.gameState.planes.length - 1; i >= 0; i--) {
      const plane = this.gameState.planes[i]
      plane.y += plane.speed
      
      // 移除超出屏幕的飞机
      if (plane.y > this.canvasHeight) {
        this.gameState.planes.splice(i, 1)
      }
    }
  },

  spawnPlanes() {
    this.gameState.planeSpawnTimer += 16
    if (this.gameState.planeSpawnTimer >= this.gameState.planeSpawnInterval) {
      this.gameState.planeSpawnTimer = 0
      
      const plane = {
        x: Math.random() * (this.canvasWidth - 40),
        y: -40,
        width: 40,
        height: 30,
        speed: 2 + Math.random() * 2
      }
      
      this.gameState.planes.push(plane)
    }
  },

  spawnEnemyBullets() {
    this.gameState.enemyBulletTimer += 16
    if (this.gameState.enemyBulletTimer >= this.gameState.enemyBulletInterval) {
      this.gameState.enemyBulletTimer = 0
      
      // 从飞机发射子弹
      this.gameState.planes.forEach(plane => {
        if (Math.random() < 0.3) { // 30%概率发射子弹
          const bullet = {
            x: plane.x + plane.width / 2,
            y: plane.y + plane.height,
            width: 4,
            height: 8,
            speed: 3 + Math.random() * 2
          }
          this.gameState.enemyBullets.push(bullet)
        }
      })
    }
  },

  checkCollisions() {
    // 检查坦克子弹与飞机的碰撞
    for (let i = this.gameState.bullets.length - 1; i >= 0; i--) {
      const bullet = this.gameState.bullets[i]
      
      for (let j = this.gameState.planes.length - 1; j >= 0; j--) {
        const plane = this.gameState.planes[j]
        
        if (this.isColliding(bullet, plane)) {
          // 击落飞机
          this.gameState.bullets.splice(i, 1)
          this.gameState.planes.splice(j, 1)
          this.setData({
            score: this.data.score + 1
          })
          break
        }
      }
    }

    // 检查敌方子弹与坦克的碰撞
    for (let i = this.gameState.enemyBullets.length - 1; i >= 0; i--) {
      const bullet = this.gameState.enemyBullets[i]
      
      if (this.isColliding(bullet, this.gameState.tank)) {
        // 坦克被击中
        this.gameState.enemyBullets.splice(i, 1)
        this.setData({
          health: this.data.health - 2
        })
        
        if (this.data.health <= 0) {
          this.gameOver()
        }
      }
    }
  },

  isColliding(rect1, rect2) {
    return rect1.x < rect2.x + rect2.width &&
           rect1.x + rect1.width > rect2.x &&
           rect1.y < rect2.y + rect2.height &&
           rect1.y + rect1.height > rect2.y
  },

  updateLevel() {
    const newLevel = Math.floor(this.data.score / 50) + 1
    if (newLevel !== this.data.level && newLevel <= 10) {
      // 关卡提升
      this.setData({
        level: newLevel
      })
      
      // 通关奖励：重新满血
      if (newLevel > 1) {
        this.setData({
          health: 10
        })
        
        // 显示通关提示
        this.showLevelUpMessage(newLevel)
      }
      
      // 增加难度
      this.gameState.planeSpawnInterval = Math.max(300, 1000 - (newLevel - 1) * 100)
      this.gameState.enemyBulletInterval = Math.max(300, 800 - (newLevel - 1) * 50)
    }
  },

  // 新增：显示关卡提升提示
  showLevelUpMessage(level) {
    // 创建关卡提升提示
    this.levelUpMessage = {
      level: level,
      showTime: Date.now(),
      duration: 3000 // 显示3秒
    }
  },

  renderGame() {
    if (!this.ctx) return
    
    // 清空画布
    this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight)
    
    // 绘制背景
    this.drawBackground()
    
    // 绘制坦克
    this.drawTank()
    
    // 绘制子弹
    this.drawBullets()
    
    // 绘制敌方子弹
    this.drawEnemyBullets()
    
    // 绘制飞机
    this.drawPlanes()
    
    // 绘制UI
    this.drawUI()
    
    // 绘制关卡提升提示
    this.drawLevelUpMessage()
  },

  drawBackground() {
    // 绘制渐变背景
    const gradient = this.ctx.createLinearGradient(0, 0, 0, this.canvasHeight)
    gradient.addColorStop(0, '#1e3c72')
    gradient.addColorStop(1, '#2a5298')
    this.ctx.fillStyle = gradient
    this.ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight)
  },

  drawTank() {
    const tank = this.gameState.tank
    
    // 如果有坦克图片且加载成功，使用图片绘制
    if (this.images.tankLoaded && this.images.tank) {
      this.ctx.drawImage(this.images.tank, tank.x, tank.y, tank.width, tank.height)
    } else {
      // 备用：绘制几何图形
      this.ctx.fillStyle = '#27ae60'
      this.ctx.fillRect(tank.x, tank.y, tank.width, tank.height)
      
      // 绘制坦克履带
      this.ctx.fillStyle = '#2c3e50'
      this.ctx.fillRect(tank.x, tank.y + tank.height - 8, tank.width, 8)
      
      // 绘制炮塔
      this.ctx.fillStyle = '#34495e'
      this.ctx.fillRect(tank.x + 8, tank.y + 8, 24, 24)
    }
    
    // 绘制炮管
    if (this.images.rivetLoaded && this.images.rivet) {
      // 使用炮管图片
      const rivetWidth = 8
      const rivetHeight = 20
      const rivetX = tank.x + tank.width / 2 - rivetWidth / 2
      const rivetY = tank.y - rivetHeight
      this.ctx.drawImage(this.images.rivet, rivetX, rivetY, rivetWidth, rivetHeight)
    } else {
      // 备用：绘制几何图形
      this.ctx.fillStyle = '#2c3e50'
      this.ctx.fillRect(tank.x + tank.width / 2 - 2, tank.y - 10, 4, 10)
    }
  },

  drawBullets() {
    this.ctx.fillStyle = '#f39c12'
    this.gameState.bullets.forEach(bullet => {
      this.ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height)
    })
  },

  drawEnemyBullets() {
    this.ctx.fillStyle = '#e74c3c'
    this.gameState.enemyBullets.forEach(bullet => {
      this.ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height)
    })
  },

  drawPlanes() {
    this.ctx.fillStyle = '#e74c3c'
    this.gameState.planes.forEach(plane => {
      this.ctx.fillRect(plane.x, plane.y, plane.width, plane.height)
      
      // 绘制飞机细节
      this.ctx.fillStyle = '#c0392b'
      this.ctx.fillRect(plane.x + 5, plane.y + 5, 30, 20)
      this.ctx.fillStyle = '#e74c3c'
    })
  },

  drawUI() {
    // 绘制分数
    this.ctx.fillStyle = '#ffffff'
    this.ctx.font = '20px Arial'
    this.ctx.fillText(`分数: ${this.data.score}`, 20, 30)
    
    // 绘制关卡
    this.ctx.fillText(`关卡: ${this.data.level}/10`, 20, 60)
    
    // 绘制血量
    this.ctx.fillStyle = '#ffffff'
    this.ctx.fillText(`血量: ${this.data.health}`, 20, 90)
    
    // 绘制血量条
    const healthBarWidth = 200
    const healthBarHeight = 20
    const healthBarX = 20
    const healthBarY = 110
    
    // 背景条
    this.ctx.fillStyle = '#34495e'
    this.ctx.fillRect(healthBarX, healthBarY, healthBarWidth, healthBarHeight)
    
    // 血量条
    const healthPercent = this.data.health / 10
    this.ctx.fillStyle = healthPercent > 0.5 ? '#27ae60' : healthPercent > 0.2 ? '#f39c12' : '#e74c3c'
    this.ctx.fillRect(healthBarX, healthBarY, healthBarWidth * healthPercent, healthBarHeight)
  },

  // 新增：绘制关卡提升提示
  drawLevelUpMessage() {
    if (!this.levelUpMessage) return
    
    const now = Date.now()
    const elapsed = now - this.levelUpMessage.showTime
    
    if (elapsed > this.levelUpMessage.duration) {
      this.levelUpMessage = null
      return
    }
    
    // 计算透明度（淡入淡出效果）
    let alpha = 1
    if (elapsed < 500) {
      alpha = elapsed / 500 // 淡入
    } else if (elapsed > this.levelUpMessage.duration - 500) {
      alpha = (this.levelUpMessage.duration - elapsed) / 500 // 淡出
    }
    
    this.ctx.save()
    this.ctx.globalAlpha = alpha
    
    // 绘制半透明背景
    this.ctx.fillStyle = 'rgba(0, 0, 0, 0.7)'
    this.ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight)
    
    // 绘制关卡提升文字
    this.ctx.fillStyle = '#f39c12'
    this.ctx.font = 'bold 48px Arial'
    this.ctx.textAlign = 'center'
    this.ctx.fillText(`🎉 第${this.levelUpMessage.level}关！`, this.canvasWidth / 2, this.canvasHeight / 2 - 50)
    
    this.ctx.fillStyle = '#2ecc71'
    this.ctx.font = '32px Arial'
    this.ctx.fillText('血量已恢复满值！', this.canvasWidth / 2, this.canvasHeight / 2 + 20)
    
    this.ctx.restore()
  },

  // 触摸事件处理 - 只处理移动，不处理射击
  onTouchStart(e) {
    if (this.data.gameOver) return
    
    const touch = e.touches[0]
    const x = touch.clientX
    const y = touch.clientY
    
    // 只处理移动，不射击
    this.moveTank(x, y)
  },

  onTouchMove(e) {
    if (this.data.gameOver) return
    
    const touch = e.touches[0]
    const x = touch.clientX
    const y = touch.clientY
    
    // 移动坦克
    this.moveTank(x, y)
  },

  onTouchEnd(e) {
    // 触摸结束事件
  },

  // 虚拟按键控制
  moveLeft() {
    this.touchState.leftPressed = true
  },

  moveRight() {
    this.touchState.rightPressed = true
  },

  moveUp() {
    this.touchState.upPressed = true
  },

  stopMove() {
    this.touchState.leftPressed = false
    this.touchState.rightPressed = false
    this.touchState.upPressed = false
  },

  // 移除手动射击功能，改为自动射击
  shoot() {
    // 这个方法现在被自动射击替代，保留是为了兼容性
    console.log('自动射击已启用')
  },

  moveTank(x, y) {
    const tank = this.gameState.tank
    
    // 限制坦克移动范围
    if (x >= 0 && x <= this.canvasWidth - tank.width) {
      tank.x = x
    }
    
    // 坦克可以向前移动一点
    if (y >= this.canvasHeight - tank.height - 50 && y <= this.canvasHeight - tank.height) {
      tank.y = y
    }
  },

  // 键盘控制
  onKeyDown(e) {
    if (this.data.gameOver) return
    
    const tank = this.gameState.tank
    const step = 20
    
    switch (e.keyCode) {
      case 37: // 左箭头
        tank.x = Math.max(0, tank.x - step)
        break
      case 39: // 右箭头
        tank.x = Math.min(this.canvasWidth - tank.width, tank.x + step)
        break
      case 38: // 上箭头
        tank.y = Math.max(this.canvasHeight - tank.height - 50, tank.y - step)
        break
      case 32: // 空格键 - 现在可以切换自动射击
        this.gameState.autoShoot = !this.gameState.autoShoot
        console.log('自动射击:', this.gameState.autoShoot ? '开启' : '关闭')
        break
    }
  },

  gameOver() {
    this.setData({
      gameOver: true
    })
    
    this.stopGameLoop()
    
    // 保存最高分
    const currentHighScore = wx.getStorageSync('highScore') || 0
    if (this.data.score > currentHighScore) {
      wx.setStorageSync('highScore', this.data.score)
    }
    
    // 延迟跳转到结果页面
    setTimeout(() => {
      wx.redirectTo({
        url: `/pages/result/result?score=${this.data.score}&level=${this.data.level}`
      })
    }, 2000)
  },

  pauseGame() {
    this.setData({
      gamePaused: !this.data.gamePaused,
      showPauseMenu: !this.data.showPauseMenu
    })
  },

  resumeGame() {
    this.setData({
      gamePaused: false,
      showPauseMenu: false
    })
  },

  quitGame() {
    wx.navigateBack()
  }
})

